package site.xuxingcan.autoclick;

import android.os.Environment;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

/**
 * Created by xuxingcan on 2016/9/6.
 */
public class RootShell {
    /**
     * 用root权限执行Linux下的Shell指令 * * @author jzj * @since 2014-09-09
     */
    private static OutputStream os;
    private static BufferedReader in;

    /**
     * 执行shell指令 * * @param cmd * 指令
     */
    public static final void exec(String cmd) {
        try {
            if (os == null) {
                Process process = Runtime.getRuntime().exec("su");
                os = process.getOutputStream();
                in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            }
            os.write(cmd.getBytes());
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static final void simulateKey(int keyCode) {
        exec("input keyevent " + keyCode + "\n");
    }

    public static final void simulateTap(int x, int y) {
        exec("input tap " + x + " " + y + "\n");
    }

    public static final void simulateText(String s) {
        exec("input text " + s + "\n");
    }

    public static final void screenCap() {
        File file = new File(Environment.getExternalStorageDirectory(), "keyShot.png");
        exec("screencap -p " + file.getAbsolutePath() + "\n");
    }

    public static final String getTopActivity() {
        exec("dumpsys window | grep mCurrentFocus\n");
        try {
//            String s = "";
//            String line = null;
//            while ((line = in.readLine()) != null) {
//                s += line + "\n";
//            }
            return in.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
